package com.linc.concurrency;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

class TaskDemo implements Runnable {

  @Override
  public void run() {
    while (true) {
      try {
        Thread.sleep(10000);
        System.out.println("Running");
      } catch (InterruptedException e) {
        e.printStackTrace();
        Thread.currentThread().interrupt();
      }
    }

    /* 收到中断请求时退出当前线程的执行
    try {
      Thread.sleep(1000);
    } catch (InterruptedException e) {
      System.out.println(e.getMessage() + "...." + e.getCause());
      break;
    }
    */
  }
}

class TaskRunnable implements Runnable {
  BlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(10);

  @Override
  public void run() {
    while (!Thread.currentThread().isInterrupted()) {
      try {
        var v = queue.take();
        System.out.println("Receive " + v);
      } catch (InterruptedException e) {
        e.printStackTrace();
        Thread.currentThread().interrupt();
      }
    }
  }
}

public class InterruptDemo {
  public static void main(String[] args) throws InterruptedException {
    /* 普通的用例
    Thread task = new Thread(new com.linc.concurrency.TaskDemo());
    task.start();
    Thread.sleep(12 * 100);
    System.out.println("sending interrupt....");
    task.interrupt();
    Thread.sleep(1000);
    System.out.println(task.getState());
    */
    var taskRun = new TaskRunnable();
    Thread thread = new Thread(taskRun);
    thread.start();
    taskRun.queue.put(100);

    Thread.sleep(100);
    thread.interrupt();
  }
}
